package org.linlinjava.litemall.wx.service;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;

import org.linlinjava.litemall.wx.dao.ModelMessage;
import org.linlinjava.litemall.wx.util.HttpRequest;
import org.linlinjava.litemall.wx.util.IsNotNullValit;
import org.linlinjava.litemall.wx.util.WxAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;

@Service
public class WxService {
	
	
	private static final Logger log = LoggerFactory.getLogger(WxService.class);

	
	@Autowired
	private WxAuth wxAuth;
	
	@Value("${wxapp.gzhAppid}")
	private String gzhAppid;
	
	@Value("${wxapp.gzhAppsecret}")
	private String gzhAppSecrit;
	
	@Value("${wxapp.tocken}")
	private String tocken;
	
	/**
	 * 根据小程序登录返回的code获取openid和session_key
	 * https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html?t=20161107
	 * @param wxcode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String,Object>getWxSession(String wxCode){
		StringBuffer sb = new StringBuffer();
		sb.append("appid=").append(wxAuth.getAppId());
		sb.append("&secret=").append(wxAuth.getSecret());
		sb.append("&js_code=").append(wxCode);
		sb.append("&grant_type=").append(wxAuth.getGrantType());
		String res = HttpRequest.sendGet(wxAuth.getSessionHost(), sb.toString());
		if(res == null || res.equals("")){
			return null;
		}
		return JSON.parseObject(res, Map.class);
	}
	
	@SuppressWarnings("unchecked")
	public synchronized String getAndSaveTocken(String appid, String secret) {
		
		Assert.notNull(appid, "appid 不能为空");
		Assert.notNull(secret, "secret 不能为空");
		
		//现在数据库表里面查找，不能经常请求，否则会失败
//		String DBtocken = this.userOperaService.findTocken();
		
		String DBtocken = null;
		
		if(IsNotNullValit.StringIsNotNull(DBtocken)) {
			return DBtocken;
		}
		
		StringBuilder builder = new StringBuilder("grant_type=client_credential&appid=");
		builder.append(gzhAppid.trim());
		builder.append("&secret=");
		builder.append(gzhAppSecrit.trim());
		
		String res = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", builder.toString());
		if(res == null || res.equals("")){
			return null;
		}
		
		Map<String,Object> result = JSON.parseObject(res, Map.class);
		
		Integer errorCode = (Integer) result.get("errcode");
		
		if(errorCode !=null) {
			
			return errorCode+"(微信公众号官网查询改API错误代码含义)";
		}
		
		String tocken = (String) result.get("access_token");
		
//		如果没有异常则插入数据库并开始计时
//		this.userOperaService.saveAndUpdateTocken(tocken);
		
		return tocken;
	}

	//发送模板消息
	public String sendModalMessage(ModelMessage mm,String tocken) {

		synchronized(mm) {
			String host = wxAuth.getMudualHost()+tocken;
			String value = JSON.toJSONString(mm);
			log.info("模板消息:"+value);
			return HttpRequest.sendPost(host, value);
		}
	}

	//校验消息模板配置
	public synchronized String ShaSignature(String timestamp, String nonce) {

		log.info("tocken = "+tocken);
		
		String[] tmparr = { tocken, timestamp, nonce };

		Arrays.sort(tmparr);

		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < tmparr.length; i++) {
			builder.append(tmparr[i]);
		}
		String raw = builder.toString();

		// SHA-1
		MessageDigest md = null;
		byte[] b = null;
		
		try {  
            md = MessageDigest.getInstance("SHA-1");  
            b = md.digest(raw.getBytes("UTF-8"));  
        }  
        catch(Exception e) {  
            e.printStackTrace();  
        }
		
		 //Turn sha-1 result to HexString  
        String result = "";  
        for (int i=0; i < b.length; i++) {  
            result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );  
        }  

		return result;
	}
}
